package lx.exalarm.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import lx.exalarm.R;
import lx.exalarm.alarm.AlarmBean;

/**
 * Created by liuxu on 15-3-6.
 */
public class WeekdayView extends LinearLayout implements View.OnClickListener {

    private SparseArray<TextView> mWeekdayMap = new SparseArray<>(7);
    private AlarmBean mAlarmBean;

    public WeekdayView(Context context) {
        super(context);
        initView();
    }

    public WeekdayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public WeekdayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        Context cxt = getContext();
        LayoutInflater inflater = LayoutInflater.from(cxt);
        inflater.inflate(R.layout.layout_weekday, this, true);

        mWeekdayMap.put(AlarmBean.WEEK_SUNDAY, (TextView) findViewById(R.id.repeat_weekday1));
        mWeekdayMap.put(AlarmBean.WEEK_MONDAY, (TextView) findViewById(R.id.repeat_weekday2));
        mWeekdayMap.put(AlarmBean.WEEK_TUESDAY, (TextView) findViewById(R.id.repeat_weekday3));
        mWeekdayMap.put(AlarmBean.WEEK_WEDNESDAY, (TextView) findViewById(R.id.repeat_weekday4));
        mWeekdayMap.put(AlarmBean.WEEK_THURSDAY, (TextView) findViewById(R.id.repeat_weekday5));
        mWeekdayMap.put(AlarmBean.WEEK_FRIDAY, (TextView) findViewById(R.id.repeat_weekday6));
        mWeekdayMap.put(AlarmBean.WEEK_SATURDAY, (TextView) findViewById(R.id.repeat_weekday7));
    }

    @Override
    public void onClick(View v) {
        synchronized (this) {
            int weekdayId = (int) v.getTag();
            boolean enabled = mAlarmBean.isDayRepeat(weekdayId);
            if (enabled) {
                mAlarmBean.setDayRepeat(weekdayId, false);
                v.setBackgroundResource(R.drawable.bkg_weekday_disabled);
            } else {
                mAlarmBean.setDayRepeat(weekdayId, true);
                v.setBackgroundResource(R.drawable.bkg_weekday_enabled);
            }
        }
    }

    public void setAlarm(AlarmBean alarm, boolean canChange) {
        mAlarmBean = alarm;
        for (int i = 0; i < mWeekdayMap.size(); i++) {
            int weekdayId = mWeekdayMap.keyAt(i);
            TextView tv = mWeekdayMap.get(weekdayId);
            tv.setClickable(canChange);
            tv.setBackgroundResource(mAlarmBean.isDayRepeat(weekdayId) ?
                    R.drawable.bkg_weekday_enabled : R.drawable.bkg_weekday_disabled);
            tv.setTag(weekdayId);
            if (canChange) {
                tv.setOnClickListener(this);
            }
        }
    }


}
